package com.zhss.eshop.common.util;

import org.springframework.cglib.beans.BeanCopier;

import java.util.HashMap;
import java.util.Map;

/**
 * @Desc: BeanCopier工具类
 * @Date: 2021-02-06
 * @Version:v1.0
 */
public class BeanCopierUtils {

    /**
     * BeanCopier 缓存Map
     */
    public static Map<String, BeanCopier> beanCopierCacheMap = new HashMap<>();

    /**
     * @Desc: 将source对象的属性拷贝到target对象中去
     * @Param source 源对象
     * @Param target 目标对象
     * @Return org.springframework.cglib.beans.BeanCopier
     * @Date: 2021/2/6
     */
    public static void copyProperties(Object source, Object target) throws Exception {
        /** Map 缓存Key*/
        String cacheKey = source.getClass().toString() + target.getClass().toString();
        BeanCopier beanCopier = null;

        // 双重交易锁，防止并发问题发生
        if (!beanCopierCacheMap.containsKey(cacheKey)) {
            synchronized (BeanCopierUtils.class) {
                if (!beanCopierCacheMap.containsKey(cacheKey)) {
                    beanCopier = BeanCopier.create(source.getClass(), target.getClass(), false);
                } else {
                    beanCopier = beanCopierCacheMap.get(cacheKey);
                }
            }
        } else {
            beanCopier = beanCopierCacheMap.get(cacheKey);
        }

        assert beanCopier != null;
        beanCopier.copy(source, target, null);
    }
}
